﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Lenovo.CFI.BLL;
using Lenovo.CFI.BLL.DicBll;
using Lenovo.CFI.BLL.DicMgr;
using Lenovo.CFI.Common;
using Lenovo.CFI.Common.Dic;
using Lenovo.CFI.Web.Helper;

namespace Lenovo.CFI.Web.VP
{
    public partial class IPList : System.Web.UI.UserControl
    {
        IdeaBl ideaBl = new IdeaBl();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                TopicBl topicBl = new TopicBl();
                List<Topic> topics = topicBl.GetTopic();
                topicBl.GetIpTopic(UserHelper.UserName);
                topics = topics.FindAll(t=> t.Status == TopicStatus.Suggestion || t.Status == TopicStatus.Execution || t.Status == TopicStatus.Closed);

                this.DdlTopic.DataSource = topics;
                this.DdlTopic.DataTextField = "Title";
                this.DdlTopic.DataValueField = "ID";
                this.DdlTopic.DataBind();

                if (topics.Count > 0)
                {
                    selectedTopic = topics[0];
                    ViewState["topicid"] = selectedTopic.ID;
                    ViewState["status"] = -1;

                    this.BindData();
                }

                MessageHelper.Prepare(this.Page);
            }
        }


        protected void DdlTopic_SelectedIndexChanged(object sender, EventArgs e)
        {
            ViewState["topicid"] = Convert.ToInt32(this.DdlTopic.SelectedValue);

            this.BindData();
        }

        protected void DdlStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            ViewState["status"] = Convert.ToInt32(this.DdlStatus.SelectedValue);

            this.BindData();

        }

        Topic selectedTopic = null;
        Dictionary<int, Idea> ideasDic = null;
        private void BindData()
        {
            int topicID = (int)ViewState["topicid"];

            if (selectedTopic == null) selectedTopic = new TopicBl().GetTopicByID(topicID);

            List<IdeaReview> reviews = new ReviewBl().GetReviewForIpOwner(topicID, UserHelper.UserName);

            int status = (int)ViewState["status"];
            if (status != -1) reviews = reviews.FindAll(r => r.IPConfirmed == (SuggestionStatus)status);

            ideasDic = new Dictionary<int, Idea>();
            foreach (Idea idea in new IdeaBl().GetIdeaByReviews(reviews)) ideasDic.Add(idea.ID, idea);

            reviews.Sort((x, y) => y.ReviewScore.CompareTo(x.ReviewScore));

            this.GvList.DataSource = reviews;
            this.GvList.DataBind();
        }


        protected void GvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // 设置行号
                ((Literal)(e.Row.FindControl("LtrNo"))).Text = String.Format("{0}", e.Row.DataItemIndex + 1);
                    
                IdeaReview review = (IdeaReview)e.Row.DataItem;
                Idea idea = ideasDic[review.IdeaID];

                ((Literal)e.Row.FindControl("LtrTitle")).Text = String.Format(@"<a href=""{0}"" target=""_blank"">{1}</a>",
                    UrlHelper.GenerateUrl("ideadetail", "id", idea.ID.ToString()), idea.Title);
                ((Literal)e.Row.FindControl("LtrOwner")).Text = idea.Owner;
                ((Literal)e.Row.FindControl("LtrType")).Text = IdeaTypeDicMgr.GetByCode(review.ReviewType).Title;
                ((Literal)e.Row.FindControl("LtrIP")).Text = review.NextIP.HasValue ? (review.NextIP.Value ? "Y" : "N") : "";


                if (idea.Status == IdeaStatus.Suggestion || idea.Status == IdeaStatus.Execution)
                {
                    ((LinkButton)e.Row.FindControl("BtnSuggestion")).Visible = true;
                }
                else
                {
                    ((LinkButton)e.Row.FindControl("BtnSuggestion")).Visible = false;
                }
            }
        }

        protected void GvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Suggestion")
            {
                int id = Convert.ToInt32(e.CommandArgument);
                ViewState["ReviewID"] = id;

                IdeaReview review = new ReviewBl().GetReviewByID(id);
                Idea idea = new IdeaBl().GetIdeaById(review.IdeaID);

                this.DdlIP.ClearSelection();
                this.DdlIP.SelectedIndex = (review.NextIP == true ? 0 : 1);

                this.OuacExecutor.Text = review.ActionExecutor;


                if (review.IPConfirmed == SuggestionStatus.None)
                {
                    this.BtnAgreeSuggestion.Enabled = true;
                    this.BtnFinishSuggestion.Enabled = true;
                }
                else if (review.IPConfirmed == SuggestionStatus.OnGoing)
                {
                    this.BtnAgreeSuggestion.Enabled = true;
                    this.BtnFinishSuggestion.Enabled = true;
                }
                else if (review.IPConfirmed == SuggestionStatus.Reject)
                {
                    this.BtnAgreeSuggestion.Enabled = false;
                    this.BtnFinishSuggestion.Enabled = false;
                }
                else if (review.IPConfirmed == SuggestionStatus.Finished)
                {
                    this.BtnAgreeSuggestion.Enabled = false;
                    this.BtnFinishSuggestion.Enabled = false;
                }

                this.MpeSuggestion.Show();
            }

        }

        protected void GvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GvList.PageIndex = e.NewPageIndex;
            this.BindData();
        }

        protected void BtnAgreeSuggestion_Click(object sender, EventArgs e)
        {
            try
            {
                new ReviewBl().IpSuggest((int)ViewState["ReviewID"], SuggestionStatus.OnGoing,
                    this.DdlIP.SelectedIndex == 0,
                    UserHelper.UserName);

                MessageHelper.RegShowJSAjax(this.BtnAgreeSuggestion, "Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnAgreeSuggestion, ex.Message, this.Page);
            }
            catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
            {
                ErrorHelper.ExceptionHanderForAjax(ex, this.BtnAgreeSuggestion, this.Page);
            }

            this.BindData();
        }

        protected void BtnFinishSuggestion_Click(object sender, EventArgs e)
        {
            try
            {
                new ReviewBl().IpSuggest((int)ViewState["ReviewID"], SuggestionStatus.Finished,
                    this.DdlIP.SelectedIndex == 0,
                    UserHelper.UserName);

                MessageHelper.RegShowJSAjax(this.BtnFinishSuggestion, "Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnFinishSuggestion, ex.Message, this.Page);
            }
            catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
            {
                ErrorHelper.ExceptionHanderForAjax(ex, this.BtnFinishSuggestion, this.Page);
            }

            this.BindData();
        }
    }
}